import logging
import sys
from pathlib import Path
from typing import Optional
from .config_loader import config

class TidyLogger:
    """统一的日志管理类"""
    
    _instance = None
    _initialized = False
    
    def __new__(cls):
        """单例模式，确保整个项目使用同一个日志配置"""
        if cls._instance is None:
            cls._instance = super(TidyLogger, cls).__new__(cls)
        return cls._instance
    
    def __init__(self):
        """初始化日志配置"""
        if not self._initialized:
            self._setup_logging()
            TidyLogger._initialized = True
    
    def _setup_logging(self):
        """设置日志配置"""
        # 从配置文件读取日志设置
        log_level = config.get("log_level", "INFO").upper()
        log_format = config.get("log_format", "%(asctime)s - %(name)s - %(levelname)s - %(message)s")
        log_file = config.get("log_file", "")
        
        # 创建根日志器
        self.root_logger = logging.getLogger("tidy_agent_chat")
        self.root_logger.setLevel(getattr(logging, log_level))
        
        # 清除现有的处理器
        self.root_logger.handlers.clear()
        
        # 创建格式化器
        formatter = logging.Formatter(log_format)
        
        # 控制台处理器
        console_handler = logging.StreamHandler(sys.stdout)
        console_handler.setLevel(getattr(logging, log_level))
        console_handler.setFormatter(formatter)
        self.root_logger.addHandler(console_handler)
        
        # 文件处理器（如果配置了日志文件）
        if log_file:
            file_handler = logging.FileHandler(log_file, encoding='utf-8')
            file_handler.setLevel(getattr(logging, log_level))
            file_handler.setFormatter(formatter)
            self.root_logger.addHandler(file_handler)
        
        # 防止日志向上传播到根日志器
        self.root_logger.propagate = False
    
    def get_logger(self, name: str) -> logging.Logger:
        """获取指定名称的日志器"""
        # 如果name已经以tidy_agent_chat开头，就不要重复添加
        if name.startswith("tidy_agent_chat."):
            return logging.getLogger(name)
        else:
            return logging.getLogger(f"tidy_agent_chat.{name}")
    
    def set_level(self, level: str):
        """动态设置日志级别"""
        log_level = level.upper()
        self.root_logger.setLevel(getattr(logging, log_level))
        for handler in self.root_logger.handlers:
            handler.setLevel(getattr(logging, log_level))
    
    def add_file_handler(self, file_path: str):
        """添加文件处理器"""
        formatter = logging.Formatter(config.get("log_format", "%(asctime)s - %(name)s - %(levelname)s - %(message)s"))
        file_handler = logging.FileHandler(file_path, encoding='utf-8')
        file_handler.setLevel(self.root_logger.level)
        file_handler.setFormatter(formatter)
        self.root_logger.addHandler(file_handler)

# 创建全局日志管理器实例
_tidy_logger = TidyLogger()

def get_logger(name: str) -> logging.Logger:
    """
    获取日志器的便捷函数
    
    使用方法:
    from .logger import get_logger
    logger = get_logger(__name__)
    logger.info("这是一条信息")
    """
    return _tidy_logger.get_logger(name)

def set_log_level(level: str):
    """
    动态设置日志级别的便捷函数
    
    使用方法:
    from .logger import set_log_level
    set_log_level("DEBUG")  # 切换到调试模式
    set_log_level("INFO")   # 切换到信息模式
    """
    _tidy_logger.set_level(level)

def add_log_file(file_path: str):
    """
    添加日志文件的便捷函数
    
    使用方法:
    from .logger import add_log_file
    add_log_file("debug.log")
    """
    _tidy_logger.add_file_handler(file_path) 